import Table from './table'
import { SLMDict } from '@/api/dataDict'
export default function commonListFactory({ name = 'CommonList', code = 'tab', tabsConfig = [], excludeSearch = [], searchConfig = [], changeType = 'C D' }) {
  const active = tabsConfig.find(e => e.active)
  const activeTab = active ? active.name : tabsConfig[0].name
  const _searchConfig = [
    { label: '单号', prop: 'code', type: 'text', value: '', placeholder: '' },
    {
      type: 'select',
      prop: 'schedule',
      label: '单据进度',
      value: '',
      placeholder: '',
      config: {
        remote: true,
        // paramField: 'keyWord',// 远程搜索参数名
        remoteUrl: `/data-dict/api/v2/dictionary/CTM_CUS_ARCHIVE_CHANGE_PROGRESS`,
        defaultProps: {
          label: 'dictName',
          value: 'dictCode'
        },
        paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
        apiHeader: {
          // 'Permission-Code': 'per_pur_order_middle_page',
          // 'Permission-App': 'slm'
        }
      }
    },
    { label: '变更申请人', prop: 'submitByName', type: 'text', value: '', placeholder: '' },
    { label: '所属办事处', prop: 'officeName', type: 'text', value: '', placeholder: '' },
    { label: '客户编码', prop: 'customerCode', type: 'text', value: '', placeholder: '' },
    { label: '客户名称', prop: 'customerName', type: 'text', value: '', placeholder: '' },
    { label: '门店名称', prop: 'shopName', type: 'text', value: '', placeholder: '' },
    { label: 'BPM流程单号', prop: 'applyNo', type: 'text', value: '', placeholder: '' },
    {
      type: 'select',
      prop: 'type',
      label: '单据类型',
      value: '',
      placeholder: '',
      config: {
        remote: false,
        // paramField: 'keyWord', // 远程搜索参数名
        // remoteUrl: `/data-dict/api/v2/dictionary/CTM_CUS_ARCHIVE_CHANGE_TYPE`,
        defaultProps: {
          label: 'dictName',
          value: 'dictCode'
        },
        paramsRaw: { appCode: 'slm', domainCode: 'marketing' },
        apiHeader: {
          // 'Permission-Code': 'per_pur_order_middle_page',
          // 'Permission-App': 'slm'
        }
      }
    }
  ].filter(e => !excludeSearch.includes(e.prop)).map(e => {
    const t = searchConfig.find(ee => ee.prop === e.prop)
    if (t) {
      return {
        ...e,
        ...t
      }
    }
    return e
  })
  searchConfig.forEach(e => {
    if (_searchConfig.every(ee => ee.prop !== e.prop)) {
      if (e.afterProp) {
        const i = _searchConfig.findIndex(ee => ee.prop === e.afterProp)
        if (i > -1) {
          _searchConfig.splice(i, 0, e)
        }
      } else {
        _searchConfig.push(e)
      }
    }
  })
  return {
    name,
    props: {
    },
    data() {
      return {
        searchConfig: _searchConfig,
        filtersRaw: [],
        paramsRaw: {},
        activeTab
      }
    },
    render(h) {
      const searchFormVm = h('search-form', {
        ref: 'searchForm',
        props: {
          searchConfig: this.searchConfig,
          labelWidth: 150
        },
        on: {
          clear: this.clearSearch,
          search: this.handleSearch,
          visibleChange: this.handleVisibleChange
        }
      })
      const tabPane = tabsConfig.map(e => {
        const tableProps = { ...e, filtersRaw: this.filtersRaw, paramsRaw: this.paramsRaw }
        if (!this.tableComponents[e.name]) {
          this.tableComponents[e.name] = Table({ defaultFiltersRaw: e.defaultFiltersRaw, defaultParamsRaw: e.defaultParamsRaw, config: e.tableConfig, changeColumn: e.changeColumn })
        }
        // table
        const table = h(this.tableComponents[e.name], {
          props: tableProps,
          on: this.$listeners,
          ref: e.name
        })

        'label name lazy'.split(' ').forEach(e => {
          delete tableProps[e]
        })
        const t = h('el-tab-pane', {
          props: {
            label: e.label,
            name: e.name,
            lazy: e.lazy === undefined ? true : e.lazy
          }
        }, [table])

        return t
      })
      const tabs = h('c-permission-tabs', {
        props: {
          value: this.activeTab,
          code,
          type: 'card'
        },
        attrs: {
          type: 'card'
        },
        on: {
          input: v => (this.activeTab = v)
        }
      }, tabPane)
      const children = [
        searchFormVm,
        tabs
      ]
      if (this.$scopedSlots.default instanceof Function) {
        children.push(...this.$scopedSlots.default())
      }
      const div = h('div', {}, children)
      return div
    },
    computed: {
    },
    watch: {
      activeTab: {
        handler(v) {
          const t = this.getActiveTable()
          t && t.initTableData('onPage')
        }
      },
      immediate: true
    },
    created() {
      this.tableComponents = Object.create(null, {})
      const type = this.searchConfig.find(e => e.prop === 'type')
      if (type) {
        const keys = changeType.split(' ')
        SLMDict('CTM_CUS_ARCHIVE_CHANGE_TYPE').then(res => {
          this.$set(type.config, 'selectData', res.data.filter(e => keys.includes(e.dictCode)).map(e => {
            return {
              label: e.dictName,
              value: e.dictCode
            }
          }))
        })
      }
    },
    beforeDestroy() {
    },
    methods: {
      clearSearch() {
        this.filtersRaw = []
        this.paramsRaw = {}
      },
      handleSearch({ filtersRaw, paramsRaw }) {
        const tmp = []
        for (const f of filtersRaw) {
          if (f.property === 'preCloseTime') {
            const v = f.value.replace(/\[|\]/g, '').split(',')
            tmp.push(
              { id: 'preCloseTime1', property: 'preCloseTime', value: `${v[0]} 00:00:00`, operator: '>=' },
              { id: 'preCloseTime2', property: 'preCloseTime', value: `${v[1]} 23:59:59`, operator: '<=' }
            )
          } else {
            f.id = Math.floor(Math.random() * 0xffffffff).toString(16)
            tmp.push(f)
          }
        }
        this.filtersRaw = tmp
        this.paramsRaw = paramsRaw
        this.refreshTableBoxData()
      },
      handleVisibleChange() {
        this.refreshTableHeight()
      },
      getActiveTable() {
        return this.$refs[this.activeTab]
      },
      refreshTableBoxData(flag) {
        this.$nextTick(() => {
          const t = this.getActiveTable()
          t && t.initTableData(flag)
        })
      },
      refreshTableHeight() {
        this.$nextTick(() => {
          const t = this.getActiveTable()
          t && t.refreshTableHeight()
        })
      }
    }
  }
}
